﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using FineUI;
using ZHDJ.Core.Caching;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;
using ZHDJ.WebPage.Picker;


namespace ZHDJ.Web.App.Share.Picker
{
    public partial class MemberMultiplePicker : PickerPageBase
    {
        /// <summary>
        /// 
        /// </summary>
        public string BranchID
        {
            get { return Request.QueryString["BranchID"] ?? ""; }
        }
        /// <summary>
        /// 已经选择的用户
        /// </summary>
        public List<string> selectUsers
        {
            get
            {
                return string.IsNullOrEmpty(hdSelectUsers.Text) ? new List<string>() :
                  hdSelectUsers.Text.Split(',').ToList();
            }
            set
            {
                if (value != null && value.Count > 0)
                {
                    hdSelectUsers.Text = string.Join(",", value.ToArray());
                    hdSelectUsersID.Text =
                        StringHelper.AddQuoteString(string.Join(",", (from u in value select u.Split('|')[0]).ToArray()));
                }
                else
                {
                    hdSelectUsersID.Text = hdSelectUsers.Text = "";
                }
            }
        }

        protected string GetGender(object Gender)
        {
            var d = Convert.ToString(Gender);
            if (d == "1")
            {
                return "女";
            }
            else if (d == "0")
            {
                return "男";
            }
            return "未知";
        }

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                BindTree();
                LoadData();
            }
        }

        private void BindData()
        {
            //绑定已选择的值
            var selected = SelectValue;
            if (selected.Count < 1)
                return;
            var selectedUser = DB.PartyOrgMembers.Where(a => selected.Contains(a.LoginID));
            //if (selectedUser.Count() < 1)
            //    return;
            var d = from u in selectedUser select u.LoginID + "|" + u.UserName;
            selectUsers = d.ToList();
            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            this.hdParentBranchID.Text = BranchID;
        }

        private void LoadData()
        {
            BindGrid();
            BindGridSelect();
        }

        /// <summary>
        /// 初始化已选择表格
        /// </summary>
        /// <returns></returns>
        private DataTable InitSelectUsersTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("LoginID1", typeof(string));
            dt.Columns.Add("UserName1", typeof(string));
            dt.Columns["LoginID1"].DefaultValue = "";
            dt.Columns["UserName1"].DefaultValue = "";
            foreach (var item in selectUsers)
            {
                var dr = dt.NewRow();
                dr["LoginID1"] = item.Split('|')[0];
                dr["UserName1"] = item.Split('|')[1];
                dt.Rows.Add(dr);
            }
            
            return dt;
        }

        private void BindTree()
        {
            TreeControlBusiness tree = new TreeControlBusiness("BranchID", "ParentBranchID", "BranchName", true, CacheKeys.Cache_Branch_Tree);
            tree.EnableClickEvent = true;
            tree.BindTreeBranch(TreeBranch);
            if (!string.IsNullOrEmpty(BranchID))
            {
                var n = TreeBranch.FindNode(BranchID);
                TreeBranch.Nodes.Clear();
                if (n != null)
                    TreeBranch.Nodes.Add(n);
            }
        }
       

        /// <summary>
        /// 绑定用户表
        /// </summary>
        private void BindGrid()
        {
            var ds = PartyOrgMember.GetMemberByBranchId(hdParentBranchID.Text,
                ttbSearchMessage.Text.Trim(), Grid1.PageIndex, Grid1.PageSize, 0, null, this.hdSelectUsersID.Text);
            Grid1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            Grid1.DataSource = ds.Tables[0];
            Grid1.DataBind();

        }

        /// <summary>
        /// 绑定已选择的用户表
        /// </summary>
        private void BindGridSelect()
        {

            GridSelect.DataSource = InitSelectUsersTable();
            GridSelect.DataBind();

        }


        #endregion

        #region Events
        protected void TreeBranch_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            hdParentBranchID.Text = e.Node.NodeID;
            BindGrid();
        }
        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            BindGrid();
        }




        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }


        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            string userID = ControlBusiness.GetSelectedDataKeyID(Grid1);
            string userName = ControlBusiness.GetSelectedDataKey(Grid1, 1);
            if (e.CommandName == "Select")
            {
                var list = new List<string>() { userID + "|" + userName };
                selectUsers = selectUsers.Union(list).ToList();
                LoadData();
            }
        }
       
        /// <summary>
        /// 选择选中的人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddSelectUsers_Click(object sender, EventArgs e)
        {
            var list = new List<string>();
            foreach (int rowIndex in Grid1.SelectedRowIndexArray)
            {
                list.Add(Convert.ToString(Grid1.DataKeys[rowIndex][0]) + "|" + Convert.ToString(Grid1.DataKeys[rowIndex][1]));

            }
            selectUsers = selectUsers.Union(list).ToList();
            LoadData();
        }

        /// <summary>
        /// 选择所有人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddAllUsers_Click(object sender, EventArgs e)
        {
            var list = new List<string>();
            var dt = PartyOrgMember.GetMemberByBranchId(hdParentBranchID.Text,
                "", 0, int.MaxValue, 0, null, this.hdSelectUsersID.Text).Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr["LoginID"] + "|" + dr["UserName"]);
            }
            selectUsers = selectUsers.Union(list).ToList();
            LoadData();
        }
        /// <summary>
        /// 移除选中的人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveSelectUsers_Click(object sender, EventArgs e)
        {
            var list = new List<string>();
            foreach (int rowIndex in GridSelect.SelectedRowIndexArray)
            {
                list.Add(Convert.ToString(GridSelect.DataKeys[rowIndex][0]) + "|" + Convert.ToString(GridSelect.DataKeys[rowIndex][1]));

            }
            selectUsers = selectUsers.Except(list).ToList();
            LoadData();
        }

        /// <summary>
        /// 移除所有的人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemoveAllUsers_Click(object sender, EventArgs e)
        {
            selectUsers = new List<string>();
            LoadData();
        }
        protected void GridSelect_RowCommand(object sender, GridCommandEventArgs e)
        {
            string userID = ControlBusiness.GetSelectedDataKeyID(GridSelect);
            string userName = ControlBusiness.GetSelectedDataKey(GridSelect, 1);
            if (e.CommandName == "Remove")
            {
                var list = new List<string>() { userID + "|" + userName };
                selectUsers = selectUsers.Except(list).ToList();
                LoadData();
            }

        }
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            if (selectUsers == null || selectUsers.Count < 1)
            {
                Alert.Show("请选择人员！", String.Empty);
                return;
            }
            List<string> value = (from u in selectUsers select u.Split('|')[0]).ToList();
            List<string> text = (from u in selectUsers select u.Split('|')[1]).ToList();
            ReturnValue(string.Join(",", value.ToArray()), string.Join(",", text.ToArray()));
        }
        #endregion

    }
}